package com.zg.common.alter.interceptor;

import com.zg.common.alter.autoconfigure.AlertProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>Description: </p>
 *
 * @author zhanfeng.liang
 * @since 2025/2/11 16:45
 */

//@Component
public class AlertInterceptor implements HandlerInterceptor {
    private final ThreadLocal<Long> startTime = new ThreadLocal<>();
    private final ConcurrentHashMap<String, AtomicInteger> errorCounter = new ConcurrentHashMap<>();
    private final AlertProperties alertProperties;

    public AlertInterceptor(AlertProperties alertConfig) {
        this.alertProperties = alertConfig;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        startTime.set(System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) {
        long duration = System.currentTimeMillis() - startTime.get();
        String path = request.getRequestURI();

        // 响应时间过长预警
        if (duration > alertProperties.getSlowThreshold()) {
            //AlertEvent event = new AlertEvent(path, "响应时间过长：" + duration + "ms");
            //SpringContext.publishEvent(event);
        }

        // 错误状态码计数
        if (alertProperties.getErrorCodes().contains(response.getStatus())) {
            errorCounter.computeIfAbsent(path, k -> new AtomicInteger(0)).incrementAndGet();
        }

        startTime.remove();
    }

    public Map<String, Integer> getErrorCounts() {
        return errorCounter.entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().get()));
    }

    public void resetErrorCounts() {
        errorCounter.clear();
    }
}